package com.ruoyi.common.scoket;

import com.aliyun.oss.event.ProgressEvent;
import com.aliyun.oss.event.ProgressListener;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;

/**
 * 重写上传文件监听器
 * @author yangz
 * @date 2023/10/11
 */
public class PutObjectProgressListener implements ProgressListener {

    private final long fileSize;
    private long bytesWritten = 0;
    private WebSocketSession session;

    public PutObjectProgressListener(WebSocketSession session, long fileSize) {
        this.session = session;
        this.fileSize = fileSize;
    }

    public String getProgress() {
        if (fileSize > 0) {
            int percentage = (int) (bytesWritten * 100.0 / fileSize);
            return percentage + "" ;
        }
        return "0";
    }

    @Override
    public void progressChanged(ProgressEvent progressEvent) {
        bytesWritten += progressEvent.getBytes();
        if (fileSize > 0) {
            int percentage = (int) (bytesWritten * 100.0 / fileSize);
            try {
                if (session.isOpen()) {
                    session.sendMessage(new TextMessage(percentage + "%"));
//                    System.out.println("上传进度="+percentage + "%");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
